Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Interface in java

Interface methods

What are Interface Methods?

Interface methods in Java are the methods that are declared within an interface. They are implicitly abstract and do not have a body. The body of the interface method is provided by the class that implements the interface.

Declaration of Interface Methods

Interface methods are declared inside an interface. They can only have the method signature (declaration), not the method body. Here is the syntax to declare an interface method:
Interface method basic syntaxinterface { return_type method_name(parameter_list); }
The return_type is the data type of the value the method returns. If the method does not return a value, its return type is void. Example of Interface Methods in Java Here’s an example of interface methods in Java:
Interface example - How to define interface methods - how to implement interface // Interface declaration interface Animal { void animalSound(); // interface method void sleep(); // interface method } // Class that implements the interface class Pig implements Animal { public void animalSound() { System.out.println("The pig says: wee wee"); } public void sleep() { System.out.println("Zzz"); } } class Main { public static void main(String[] args) { Pig myPig = new Pig(); // Create a Pig object myPig.animalSound(); myPig.sleep(); } }

Output

The pig says: wee wee Zzz
In this example, Animal is an interface that has two methods: animalSound() and sleep(). The class Pig implements Animal and provides the implementation for these methods.

Important Points about Interface Methods

✦ Interface methods are implicitly public and abstract. ✦ They cannot have a body. ✦ The body of the interface method is provided by the class that implements the interface. ✦ Since Java 8, an interface can have default and static methods. ✦ Since Java 9, an interface can have private methods. Remember, an interface in Java is a collection of methods. You can use it to define a set of behaviors that a class should implement. A class can implement multiple interfaces, and all the methods defined in an interface must be implemented by any class that implements it.

  📌TAGS

★Class ★ Method ★ Object ★ java ★ oops ★ Interface

Tutorials